<template>
  <div class="category-list">
    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加分类
      </el-button>
      <el-button @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 分类列表 -->
    <el-card class="list-card" shadow="hover">
      <el-table
        :data="categoryList"
        stripe
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="分类名称" min-width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="assetCount" label="资产数量" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button link type="warning" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button link type="danger" size="small" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input 
            v-model="form.name" 
            placeholder="请输入分类名称" 
            maxlength="50" 
            show-word-limit 
          />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="4"
            placeholder="请输入分类描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh } from '@element-plus/icons-vue'
import { categoryApi } from '@/api'

const router = useRouter()
const route = useRoute()

// 分类列表数据
const categoryList = ref<any[]>([])

// 加载状态
const loading = ref(false)
const submitting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加分类')
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  name: '',
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 添加分类
const handleAdd = () => {
  dialogTitle.value = '添加分类'
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row: any) => {
  // 默认使用弹框式编辑
  dialogTitle.value = '编辑分类'
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除分类
const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除分类"${row.name}"吗？删除后该分类下的资产将无法正常显示。`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await categoryApi.delete(row.id)
      ElMessage.success('删除成功')
      loadData()
    } catch (e: any) {
      ElMessage.error(e?.message || '删除失败')
    }
  }).catch(() => {/* 用户取消 */})
}

// 刷新数据
const handleRefresh = () => {
  loadData()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const payload: any = {
      ...form,
      status: 1
    }

    if (form.id) {
      await categoryApi.update(form.id, payload)
      ElMessage.success('编辑成功')
    } else {
      await categoryApi.add(payload)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    loadData()
  } catch (e: any) {
    // 拦截器已统一处理
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    id: null,
    name: '',
    description: ''
  })
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const list: any = await categoryApi.getAll()
    categoryList.value = (list || []).map((c: any) => ({
      ...c,
      createTime: c.createdAt
    }))
  } finally {
    loading.value = false
  }
}

// 监听路由参数，处理直接访问编辑页面的情况
watch(() => route.params, (params) => {
  if (params.id && route.name === 'CategoryEdit') {
    const categoryId = parseInt(params.id as string)
    const category = categoryList.value.find(item => item.id === categoryId)
    if (category) {
      handleEdit(category)
    } else {
      ElMessage.error('分类不存在')
      router.push('/category/list')
    }
  }
}, { immediate: true })

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.category-list {
  padding: 0;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.list-card {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 